<template>
  <el-select :disabled="disabled" :style="{
    width: width
  }" :value="innerValue" :multiple="multiple" filterable :placeholder="placeholder" @input="updateValue">
    <template v-if="group">
      <el-option-group  v-for="groupOption in groupOptions" :key="groupOption.label" :label="groupOption.label">
        <el-option v-for="item in groupOption.options" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-option-group>
    </template>
    <template v-else>
      <el-option  v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
      </el-option>
    </template>


  </el-select>
</template>
<!-- 
  使用示例
  类型 user dept asset car
  
  //单选
  <group-select v-model="form.recipient" :group_list="['user']" />
  //多选
  <group-select v-model="form.recipient" :group_list="['user']" :multiple="true"/>

  //分组多选
  <group-select v-model="form.recipient" :group_list="['user','dept']" :multiple="true"/>
-->
<script>
import { userList , studentList , curriculumList } from "@/api/common";
export default {
  name: 'groupSelect',
  props: {
    value: {
      default: function () {
        return [];
      },
      type: [Number, String, Array]
    },
    group_list: {
      default: function () {
        return ['user'];
      }
    },
    group_query: {
      default: function () {
        return {
        };
      }
    },
    placeholder: {
      default: '选择所属分类'
    },
    disabled: {
      default: false
    },
    multiple: {
      default: false
    },
    width: {
      default: '100%'
    },
    is_group: {
      default: false
    }
    
  },
  watch: {
    value(newValue) {
      this.innerValue = newValue;
    },
    group_query: {
      handler(newValue, oldValue) {
        //查询参数有变化
        console.log('查询参数有变化',newValue,oldValue);
        this.init();
      },
      deep: true,
      immediate: false
    },
    userList: {
      handler(newValue, oldValue) {
        this.$emit('userListChange', newValue);
      },
      deep: true,
      immediate: true
    },
    curriculumList: {
      handler(newValue, oldValue) {
        this.$emit('curriculumListChange', newValue);
      },
      deep: true,
      immediate: true
    },
  },
  data() {
    return {
      innerValue: this.value, // 使用内部变量来存储当前值
      userList: [],//用户列表
      studentList: [],//学生列表
      curriculumList: [],//课程列表
      groupOptions: [],//分组
      groupOptionsObj: {},//分组对象
      options: [],//未分组
      group: false,
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.groupOptions = [];
      this.options = [];
      var group_list = this.group_list;

      //循环需要获取的内容
      var i = 0;
      group_list.forEach(element => {
        var query = this.group_query[element];

        if (element == 'user') {
          this.getUserList(query,i);
          i++;
        } else if (element == 'curriculum') {
          this.getCurriculumList(query);
          i++;
        } else if (element == 'student') {
          this.getStudentList(query);
          i++;
        }
      });

      if (i > 1 || this.is_group) {
        // console.log('分组类型');
        this.group = true;
      } else {
        // console.log('普通类型');

      }

    },
    // 当treeselect的值发生变化时触发  
    updateValue(newValue) {
      this.$emit('input', newValue); // 通知父组件更新value  
    },
    sortGroupOptions(){
      var arr = [];
      var group_list = this.group_list;
      var groupOptionsObj = this.groupOptionsObj;
      for (let index = 0; index < group_list.length; index++) {
        const element = group_list[index];
        if(groupOptionsObj[element]){
          arr.push(groupOptionsObj[element]);
        }
      }
      this.groupOptions = arr;
    },
    getUserList(query = {},group_index) {
      //查询用户列表限制
      if(!query.hasOwnProperty("userType")){
        
      }

      userList(query).then(response => {
        this.userList = response.rows;
        // this.groupOptions.push(this.setGroupOptions(this.userList, 'userId', 'nickName', '用户', '1', ':'));
        this.groupOptionsObj['user'] = this.setGroupOptions(this.userList, 'userId', 'nickName', '用户', '1', ':');
        this.options = this.setGroupOptions(this.userList, 'userId', 'nickName');
        this.sortGroupOptions();

      });
    },
    getCurriculumList(query = {}) {
      curriculumList(query).then(response => {
        this.curriculumList = response.rows;
        this.options = this.setGroupOptions(this.curriculumList, 'id', 'name');
      });
    },
    getStudentList(query = {}) {
      studentList(query).then(response => {
        this.studentList = response.rows;
        this.options = this.setGroupOptions(this.studentList, 'id', 'name');
      });
    },
    
    //生成分组选择数据
    setGroupOptions(list, value_field = '', label_field = '', group_name = '', type = '', split = '') {
      var arr = [];
      var options = list.map(item => {
        return {
          value: `${type}${split}` + item[value_field],
          label: item[label_field] ? item[label_field] : '未设置名称'
        }
      });

      if (group_name != '') {
        arr = {
          label: group_name,
          options: options
        }
      } else {
        arr = options;
      }
      // console.log('select参数', arr);
      return arr;
    },
  }
}
</script>

<style lang="scss" scoped></style>
